package com.yulang.security.handler;

import com.yulang.security.properties.CustomSpringSecurityProperties;
import com.yulang.security.config.LoginResponseType;
import com.yulang.security.result.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 认证成功处理器 决定是响应json 还是跳转页面
 */
@Component("customAuthSuccessHandler")
public class CustomAuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Autowired
    private CustomSpringSecurityProperties customSpringSecurityProperties;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest,
                                        HttpServletResponse httpServletResponse,
                                        Authentication authentication) throws IOException, ServletException {

        if(LoginResponseType.JSON.name().equals(customSpringSecurityProperties.getAuth().getLoginType())) {
            httpServletResponse.setContentType("application/json;charset=UTF-8");
            httpServletResponse.getWriter().write(Result.ok().toJsonString());
            httpServletResponse.getWriter().flush();
        }else{
            // httpServletResponse.sendRedirect("/");
            super.onAuthenticationSuccess(httpServletRequest,httpServletResponse,authentication);
        }
    }
}
